package cn.itcast.hiss.process.activiti.multilnstance;

import cn.itcast.hiss.common.SystemConstant;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityManager;
import org.activiti.engine.task.Task;

import java.util.ArrayList;
import java.util.List;

/*
 * @author miukoo
 * @description //实现前加签功能
 * @date 2023/10/17 10:30
 * @version 1.0
 **/
public class AddSequenceMultiInstanceCmd implements Command {

    private String userId;
    private Task task;

    public AddSequenceMultiInstanceCmd(Task task, String userId){
        this.task = task;
        this.userId = userId;
    }
    // 主要修改变量
    @Override
    public Object execute(CommandContext commandContext) {
        TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
        TaskEntity taskEntity = taskEntityManager.findById(task.getId());
        // nrOfInstances
        Integer nrOfInstances = Integer.valueOf(""+taskEntity.getVariable(SystemConstant.MULTILINSTANCE_NUMBER_OF_INSTANCES));
        nrOfInstances+=2;
        taskEntity.setVariable(SystemConstant.MULTILINSTANCE_NUMBER_OF_INSTANCES,nrOfInstances);
        // nrOfCompletedInstances: 在完成当前任务时，框架会自动增加
        // assigneeList 人员集合
        List<String> userList = (List<String>) taskEntity.getVariable(SystemConstant.MULTILINSTANCE_ASSIGNEE_LIST);
        List<String> newUserList = new ArrayList<>();
        for (String user : userList) {
            newUserList.add(user);
            if(user.equals(task.getAssignee())){
                newUserList.add(userId);
                newUserList.add(task.getAssignee());
            }
        }
        taskEntity.setVariable(SystemConstant.MULTILINSTANCE_ASSIGNEE_LIST,newUserList);
        return null;
    }

}